﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;
using Fayshine.VA.Models;
using Visifire.Charts;
using Fayshine.VA.Helpers;

namespace Fayshine.VA.Views.SearchStatistics
{
    public partial class MultiDurationCompareStatistics : Page
    {
        private SearchStatisticsViewModel m_ViewModel;

        public MultiDurationCompareStatistics()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MultiDurationCompareStatistics_Loaded);
        }

        #region Event Methods

        private void MultiDurationCompareStatistics_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            this.startDatePicker.SelectedDate = DateTime.Now;
            this.endDatePicker.SelectedDate = DateTime.Now;

            this.startDatePicker2.SelectedDate = DateTime.Now;
            this.endDatePicker2.SelectedDate = DateTime.Now;

            m_ViewModel = new SearchStatisticsViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        private void m_ViewModel_AppendHistoryPassengerFlow(string title,bool isIn, List<HistoryPassengerFlow> firstHistoryPassengerFlow, List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                RenderAs type = cmbStyle.SelectedIndex == 0 ? RenderAs.Line : RenderAs.Column;
                DataSeries series = ChartHelper.GetDataSeries(type, firstHistoryPassengerFlow[0].DisplayTitle, ChartValueTypes.Auto);
                series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayValue"));
                
                string path = isIn ? "InCount" : "OutCount";
                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", path));
                series.DataSource = firstHistoryPassengerFlow;
                vcChart.Series.Add(series);

                DataSeries series2 = ChartHelper.GetDataSeries(type, secondHistoryPassengerFlow[0].DisplayTitle, ChartValueTypes.Auto);
                series2.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayValue"));
                series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", path));
                series2.DataSource = secondHistoryPassengerFlow;
                vcChart.Series.Add(series2);

                List<HistoryPassengerFlow> sources = new List<HistoryPassengerFlow>();
                HistoryPassengerFlow a1 = new HistoryPassengerFlow();
                a1.DisplayTitle = firstHistoryPassengerFlow[0].DisplayTitle;
                a1.InCount = firstHistoryPassengerFlow.Select(s => s.InCount).Sum();
                a1.OutCount = firstHistoryPassengerFlow.Select(s => s.OutCount).Sum();
                sources.Add(a1);

                HistoryPassengerFlow a2 = new HistoryPassengerFlow();
                a2.DisplayTitle = secondHistoryPassengerFlow[0].DisplayTitle;
                a2.InCount = secondHistoryPassengerFlow.Select(s => s.InCount).Sum();
                a2.OutCount = secondHistoryPassengerFlow.Select(s => s.OutCount).Sum();
                sources.Add(a2);

                DataSeries series3 = ChartHelper.GetDataSeries(RenderAs.Column, secondHistoryPassengerFlow[0].DisplayTitle, ChartValueTypes.Auto);
                series3.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel","DisplayTitle"));
                series3.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
                series3.DataMappings.Add(ChartHelper.GetDataMapping("YValue", path));
                series3.DataSource = sources;
                vcChart2.DataPointWidth = 10;
                vcChart2.View3D = true;
                vcChart2.Series.Add(series3);
                
                this.dataGrid.ItemsSource = sources;

                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = false;

            });
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (vcChart != null)
                {
                    vcChart.Series.Clear();
                    vcChart2.Series.Clear();
                }
            });
        }

        private void cmbAreas_DropDownOpened(object sender, EventArgs e)
        {

        }

        private void cmbAreas_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                if (selectedArea.Count > 0)
                {
                    cbItemDisplay.Content = selectedArea.Count > 1 ? selectedArea[0].Name + "..." : selectedArea[0].Name;

                    if (selectedArea.Count > 1)
                    {
                        this.cmbPassenger.IsEnabled = false;
                    }
                    else
                    {
                        this.cmbPassenger.IsEnabled = true;
                    }

                }
                else
                {
                    cbItemDisplay.Content = string.Empty;
                }
                cmbAreas.SelectedItem = null;
                cmbAreas.SelectedItem = cbItemDisplay;

                m_ViewModel.SelectAreasChanged(selectedArea);
                cmbPassenger_DropDownClosed(null, null);
            }
        }

        private void cmbPassenger_DropDownOpened(object sender, EventArgs e)
        {
        }

        private void cmbPassenger_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                var selectMonitorAreaExts = m_ViewModel.MonitorAreaGateExts.Where(a => a.IsSelected).ToList();

                if (selectMonitorAreaExts.Count > 0)
                {
                    cbItemDisplay2.Content = selectMonitorAreaExts.Count > 1 ? selectMonitorAreaExts[0].Name + "..." : selectMonitorAreaExts[0].Name;

                }
                else
                {
                    cbItemDisplay2.Content = string.Empty;
                }
                cmbPassenger.SelectedItem = null;
                cmbPassenger.SelectedItem = cbItemDisplay2;
            }
        }

        #endregion

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {


        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {

            if (!m_ViewModel.IsConditionSelected())
            {
                MessageBox.Show("请选择店铺或者门面！");
                return;
            }

            DateTime startTime1 = new DateTime(startDatePicker.SelectedDate.Value.Year,
                                               startDatePicker.SelectedDate.Value.Month,
                                               startDatePicker.SelectedDate.Value.Day,
                                               0, 0, 0);
            DateTime endTime1 = new DateTime(endDatePicker.SelectedDate.Value.Year,
                                             endDatePicker.SelectedDate.Value.Month,
                                             endDatePicker.SelectedDate.Value.Day,
                                             23, 59, 59);

            DateTime startTime2 = new DateTime(startDatePicker2.SelectedDate.Value.Year,
                                   startDatePicker2.SelectedDate.Value.Month,
                                   startDatePicker2.SelectedDate.Value.Day,
                                   0, 0, 0);
            DateTime endTime2 = new DateTime(endDatePicker2.SelectedDate.Value.Year,
                                             endDatePicker2.SelectedDate.Value.Month,
                                             endDatePicker2.SelectedDate.Value.Day,
                                             23, 59, 59);

            if (endTime1 < startTime1 || endTime2 < startTime2)
            {
                MessageBox.Show("结束时间不能小于开始时间");
            }
            else if (startTime1 == startTime2 && endTime1 == endTime2)
            {
                MessageBox.Show("两个时段不能相同！");
            }
            else
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                bool isIn = true;
                isIn = cmbInorOut.SelectedIndex == 0 ? true : false;
                m_ViewModel.RefreshDurationPassenger(isIn, startTime1, endTime1, startTime2, endTime2);
            }

        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }

    }
}
